import React from 'react';
import styles from './index.less';
import { Tree } from 'antd';
import IconFont from '@/components/IconFont';
import { TreeProps } from 'antd/lib/tree';
import { EventDataNode, DataNode } from 'antd/lib/tree';

export type updateTreeDataProps = (
  list: DataNode[],
  key: React.Key,
  children: DataNode[],
) => DataNode[];
//更新
export function updateTreeData(list: DataNode[], key: React.Key, children: DataNode[]): DataNode[] {
  return list.map((node) => {
    if (node.key === key) {
      return {
        ...node,
        children,
      };
    } else if (node.children) {
      return {
        ...node,
        children: updateTreeData(node.children, key, children),
      };
    }
    return node;
  });
}
const TreeComponent: React.FC<
  TreeProps & {
    updateData: (key: number | string, updateTreeData: updateTreeDataProps) => void;
  }
> = ({ updateData, ...rest }) => {
  const onLoadData = (props: EventDataNode) => {
    const { key, children } = props;
    return new Promise(async (resolve) => {
      if (children) {
        resolve();
        return;
      }

      await updateData(key, updateTreeData);
      resolve();
    });
  };
  return (
    <Tree
      switcherIcon={<IconFont type={'iconzhucaidanzhankai'} className={styles['expand']} />}
      className={styles['tree-wrap']}
      loadData={onLoadData}
      {...rest}
    />
  );
};

export default TreeComponent;
